package framework.webserver;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.client.otdr.OtdrDomainService;
import org.eclipse.jetty.server.Handler;
import org.eclipse.jetty.server.Request;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.server.handler.AbstractHandler;
import org.eclipse.jetty.server.handler.HandlerCollection;
import org.eclipse.jetty.webapp.WebAppContext;
import framework.DomainService;

public class RestServer {
	private DomainService service;
	
	public static void main(String[] arg) {
		new RestServer(new OtdrDomainService()).start();
	}
	
	public RestServer(DomainService service) {
		this.service = service;
	}
	
	public void start() {
		new Thread() {

			@Override
			public void run() {
				initialize();
			}
			
		}.start();
	}
	
	private void initialize() {
		int port = 8080;
		Server server = new Server(port);
        
        String xmlPath = this.getClass().
     	       getClassLoader().getResource("framework/webserver/web.xml").toExternalForm();
        String resourcePath = this.getClass().
  	       getClassLoader().getResource("framework/webserver").toExternalForm();
        
        HandlerCollection handlers = new HandlerCollection();
                
        // Jersey Servlet
        WebAppContext webAppContext = new WebAppContext();
        webAppContext.setDescriptor(xmlPath);   
        webAppContext.setResourceBase(resourcePath);
        webAppContext.setServer(server);
        webAppContext.setContextPath("/");
        handlers.addHandler(webAppContext);
       	    
        handlers.addHandler(getHandler(service));
        service.addWebHandler(new WebHandler() {
			@Override
			public void stateChanged(String message) {
				MyWebSocket.fireMessage(message);
			}
        });
                
        server.setHandler(handlers);

        try {
            System.out.println(">>> STARTING EMBEDDED JETTY SERVER, PRESS ANY KEY TO STOP");
            server.start();
            server.join();
            while (System.in.available() == 0) {
                Thread.sleep(5000);
            }
            server.stop();
            
        } catch (Exception e) {
            e.printStackTrace();
            System.exit(100);
        }
	}

	private Handler getHandler(final DomainService service) {
		return new AbstractHandler() {

			@Override
			public void handle(String target,
                    Request baseRequest,
                    HttpServletRequest request,
                    HttpServletResponse response)
					throws IOException, ServletException {
				
				String line = request.getParameter("command");
				if (line == null) {
					return;
				}
				service.webRequestReceived(line);
			}
			
		};
	}
}
